<?php
/**
 * controller基类
 */
class Controller_Base{
	private $_tpl = '';	//模板文件
	private $_tpl_path = '';
	private $_v;		//模板传值
	private $_shutdown_info_on;
	
	public function __construct(){
		if (!defined('BASEDIR')) exit('Sorry, you went into a wrong way!');
		if(get_class($this) == __CLASS__){
			exit("Controller基类不允许直接访问!");
		}
		$this->_tpl_path = BASEDIR."view/".strtolower(str_ireplace(array('Controller_','_'), '/', get_class($this))).'/';
		$this->shutdown_info_on();
	}
    
	public function __destruct(){
		if($this->_shutdown_info_on){
			global $start_mt, $db_query_count;
			echo("<p style=\"text-align:center; font-size:9.5pt; margin-top:20px;\">服务器君用时".
				(microtime(true)-$start_mt)."秒,历经".$db_query_count."次数据库查询为您呈现此页</p>");
		}
	}
	
	/**
	 * 检查登录
	 */
	public function checkLogin(){
		if(!isset($_SESSION['uid'])){
			$this->redirect("您需要先登录本系统！",BASE_URL,5);
		}
	}
	
	/**
	 * 页面跳转
	 */
	public function redirect($msg="您无权访问此页面！",$url=BASE_URL,$sec=3){
		echo '<div style="margin:auto;margin-top:30px;text-align:center;padding:30px;">'.
			'<h3 style="font-family:黑体;">'.t::out($msg)."</h3><br />页面将在".$sec.'秒后跳转，如未自动跳转，请点击'.
			'<a href="'.$url.'" target="_self">'.$url.'</a>';
		echo '<script>setTimeout(function(){window.location.href="'.$url.'";},'.($sec*1000).')</script>';
		exit();
	}
	
	/**
	 * 开关页底部显示数据统计
	 */
	public function shutdown_info_on($on=1){
		$this->_shutdown_info_on = $on;
	}
	
	/**
	 * 设定显示模板
	 */
	public function view($tpl = 'index'){
		if(file_exists($this->_tpl_path.$tpl.'.phtml')){
			$this->_tpl = $this->_tpl_path.$tpl.'.phtml';
		}elseif(file_exists(TPL_DIR.$tpl.'.phtml')){
			$this->_tpl = TPL_DIR.$tpl.'.phtml';
		}else{
			exit("Error:模板文件缺失...(".str_ireplace(BASEDIR, '', $this->_tpl_path).$tpl.'.phtml)');
		}
		return $this;
	}
    
	/**
	 * 绑定CSS
	 */
    public function bindCss($css){
    	if(file_exists(CSS_DIR.$css)){
        	$this->_v['css'] []= CSS_URL.$css;
		}
        return $this;
    }
	
	/**
	 * 绑定JS
	 */
    public function bindJs($js){
        if(file_exists(JS_DIR.$js)){
        	$this->_v['js'] []= JS_URL.$js;
		}
        return $this;
    }
    
	/**
	 * 绑定变量
	 */
	public function bind($k,$v=null){
		if(is_array($k) && $v==null){	//传入数组批量设置
			foreach($k as $k1=>$v1){
				$this->bind($k1,$v1);
			}
		}else{
			if($k!='css' && $k!='js'){
				$this->_v [$k]= $v;
			}			
		}
		return $this;
	}
	
	/**
	 * 页面输出至客户端
	 */
	public function show(){
		ob_start();
		$B = &$this->_v;
		if($this->_tpl)	include $this->_tpl;
		ob_end_flush();
	}
	
	/**
	 * 页面输出到变量
	 */
	public function data(){
		ob_start();
		$B = &$this->_v;
		if($this->_tpl)	include $this->_tpl;
		return ob_get_clean();
	}	
	
	/**
	 * 输出json格式字符串
	 */
	public function json($arr){
		$this->shutdown_info_on(0);
		exit(json_encode($arr));
	}
	
}